
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class shipMovementNew : MonoBehaviour 
{
	private float mouseX;
	private float mouseY;
	
	private Vector3 worldPos;

	public int MaxMovement;
	public string tag;
	
	private int CurrMovement;
		
	public TurnAndPlayerVariables tpvScript;
	public AudioClip sound_selected;
	
	private List<Vector3> movePointList;
	
	void Start()
	{	
		tpvScript.AddShipToList(tag);
		tpvScript.DeselectAll();
		
		movePointList = new List<Vector3>();
		
		CurrMovement = MaxMovement;
	}
	
	
	void OnMouseOver()
	{
		if(Input.GetMouseButtonDown(0) && !tpvScript.AnySelected())
		{
			tpvScript.SetSelectedShip(tag);
			AudioSource.PlayClipAtPoint(sound_selected,transform.position);
		}
	}
	
	void Update()
	{		
		if (tpvScript.IsShipSelected(tag) && CurrMovement > 0 && Input.GetMouseButtonDown(0))
		{
			Debug.Log ("GetMouseButton 1\n");
			mouseX = Input.mousePosition.x;
			mouseY = Input.mousePosition.y;
			
			worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mouseX, mouseY, 10));
			
			Vector3 distance;
			distance.x = worldPos.x - transform.position.x;
			distance.y = worldPos.y - transform.position.y;
			distance.z = transform.position.z;
			
			int totalDis = (int)Mathf.Sqrt(Mathf.Pow(distance.x,2) + Mathf.Pow(distance.y,2));
			
			if (totalDis < CurrMovement)
			{
				movePointList.Add(worldPos);
				CurrMovement -= totalDis;
				Debug.Log ("Point Added - Distance < Current\n");
			}
			else
			{
				Vector3 maxTranslation = distance.normalized * CurrMovement;
				movePointList.Add (maxTranslation);
				CurrMovement = 0;
				Debug.Log("Point Added - Max Distance\n");
			}
				
			
			//transform.position = worldPos;
		}
			
		if (tpvScript.IsShipSelected(tag) && Input.GetMouseButtonDown(1))
		{
			Debug.Log ("GetMouseButton2\n");
			if (movePointList.Count == 0)
			{
				tpvScript.DeselectShip(tag);
			}
			else
			{
				movePointList.RemoveAt(movePointList.Count-1);
			}
		}
		
		if (tpvScript.IsShipSelected(tag) && Input.GetKeyDown(KeyCode.Return))
		{
			Debug.Log ("Enter Key\n");
			transform.position = movePointList[movePointList.Count-1];
			movePointList.Clear();
		}
		
		if (tpvScript.IsShipSelected(tag) && Input.GetKeyDown(KeyCode.Escape))
		{
			Debug.Log("Escape Key\n");
			tpvScript.DeselectShip(tag);
			movePointList.Clear();
		}
	}
}